import json
import random
import string
import time
from datetime import datetime

import flask_socketio
from flask_socketio import emit, join_room, leave_room
import uuid
from extension import socketio, db
from flask_socketio import emit, join_room, leave_room
from flask import Blueprint, request, jsonify
from models.miniprogram_model import Room, RoomPlayer, User, Round

bp = Blueprint('mysqlroom', __name__, url_prefix='/mysqlroom')


# index界面调用
@bp.route('/create_room', methods=['POST'])
def create_room():
    data = request.get_json()
    if not data:
        return jsonify({'error': '缺少JSON数据'}), 400
    # 验证必需参数
    creator_id = data.get('creatorId')
    if not creator_id:
        return jsonify({'error': '缺少创建者用户ID'}), 400
    # 验证用户是否存在
    user = User.query.get(creator_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    # # 验证规则配置是否存在
    # rule = RuleConfig.query.get(rule_config_id)
    # if not rule:
    #     return jsonify({'error': '规则配置不存在'}), 404

    #？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？？
    rule_config_id = data.get('rule_config_id', 1)  # 默认使用ID为1的规则
    max_players = data.get('max_players', 4)
    name = data.get('name', "飞翔的企鹅的房间")
    while True:
        # 生成唯一房间码--随机数orUUID？
        # room_code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
        room_id = str(uuid.uuid4())  # 生成唯一房间ID
        if not Room.query.filter_by(id=room_id).first():
            break
    try:
        # 开启数据库事务
        with db.session.begin_nested():
            # 创建房间
            room = Room(
                id=room_id,
                creator_id=creator_id,
                name=name,
                rule_config_id=rule_config_id,
                max_players=max_players,
                status=1,  # 1: 等待中+
                members={
                    str(creator_id): {  # 直接用用户ID作为键（转为字符串，JSON要求键为字符串）——————————————这里注意下看看怎么处理下，因为user1~4的顺序要固定那就要使用1234  但是现在为什么要用userid索引
                        'user_id':creator_id,
                        'nickname': user.nickname,
                        'avatar': user.avatar,
                        'score': 0,
                        'isWinner': False
                    }
                }
            )
            db.session.add(room)
            db.session.flush()  # 获取新创建的房间ID
            # 创建关联，并将创建者添加为房主
            room_player = RoomPlayer(
                room_id=room.id,
                user_id=creator_id,
                nickname=user.nickname,
                avatar=user.avatar,
                is_owner=True,
                status=1  # 1: 在线
            )
            db.session.add(room_player)
            # 更新房间的当前玩家数
            room.current_players = 1
        # 提交事务
        db.session.commit()
        # 返回创建成功的房间信息
        return jsonify({
            'room_id': room.id,
            'message': '房间创建成功'
        }), 201
        # flask_socketio.join_room(room_id)
    except Exception as e:
        db.session.rollback()
        print(e)
        # app.logger.error(f"创建房间失败: {str(e)}")
        return jsonify({'error': '服务器内部错误', 'details': str(e)}), 500

# @socketio.on('jinfangjian')
# def handle_jinfangjin(data):
@bp.route('/join_room', methods=['POST'])
def handle_join_room():
    data = request.get_json()
    if not data:
        return jsonify({'error': '缺少JSON数据'}), 400
    room_id = data.get('roomId')
    user_id = data.get('userId')
    if not room_id or not user_id:
        return jsonify({'error': '缺少必要参数（room_id/user_id）'}), 400
    # 查询用户和房间
    user = User.query.get(user_id)
    if not user:
        return jsonify({'error': '用户不存在'}), 404
    room = Room.query.get(room_id)
    if not room:
        return jsonify({'error': '房间不存在'}), 404
    # 解析房间成员
    try:
        members = json.loads(room.members) if isinstance(room.members, str) else room.members
    except json.JSONDecodeError:
        members = {}
        print(f"解析房间成员失败: {room.members}")
    # 检查房间容量和重复加入
    if len(members) >= room.max_players:
        return jsonify({'success': False, 'error': '房间已满'}), 400
    if str(user_id) in members:
        print("已加入---------------------------------------------------------------------------------------")
        return jsonify({
            'success': True,
            'message': '已加入',
            'room_id': room_id
        }), 200
    try:
        with db.session.begin_nested():
            # 创建房间玩家记录
            new_room_player = RoomPlayer(
                user_id=user_id,
                room_id=room_id,
                nickname=user.nickname,
                avatar=user.avatar,
                is_owner=False,
                status=1,
                join_time=datetime.now()
            )
            db.session.add(new_room_player)
            # 更新房间成员和人数
            new_member = {
                'user_id': user_id,
                'nickname': user.nickname,
                'avatar': user.avatar,
                'score': 0,
                'isWinner': False
            }
            members[str(user_id)] = new_member
            room.members = json.dumps(members)
            room.current_players = len(members)
        db.session.commit()
        # 注意：HTTP接口中不能调用 join_room 或 emit（无WebSocket连接）
        # 前端加入房间后，需通过WebSocket连接通知其他成员（见下方补充）
        print('-----------------------------------------------------------------------------------------------------------------room_id',room_id)
        return jsonify({
            'success': True,
            'message': '加入房间成功',
            'room_id': room_id
        }), 200
    except Exception as e:
        db.session.rollback()
        print(f"加入房间失败: {e}")
        return jsonify({'error': '服务器内部错误', 'details': str(e)}), 500


# 补充：WebSocket 事件处理（用户加入房间后的通知）  弃用了
@socketio.on('user_joined_notify')  # 前端加入房间后主动触发此事件
def handle_user_joined_notify(data):
    room_id = data.get('room_id')
    user_id = data.get('user_id')
    if not room_id or not user_id:
        return emit('error', {'message': '缺少room_id/user_id'})
    # 获取用户信息并广播给房间内其他成员
    user = User.query.get(user_id)
    if user:
        new_member = {
            'nickname': user.nickname,
            'avatar': user.avatar
        }
        res_data={"room_id":room_id,"user_id":user_id,"userinfo":new_member}
        join_room(room_id)  # 此处是 WebSocket上下文，可正常使用 join_room
        emit('user_joined', res_data, room=room_id)  # 广播给房间内所有连接
# def handle_join_room():
#     data = request.get_json()
#     print(f"收到加入房间请求: {data}")
#     room_id = data.get('room_id')
#     user_id = data.get('user_id')
#     if not room_id or not user_id:
#         print('缺少必要参数')
#         return
#     # 查询用户信息
#     user = User.query.get(user_id)
#     if user is None:
#         print(f"未找到用户 ID 为 {user_id} 的用.户")
#         return
#
#     # 查询房间信息
#     room = Room.query.get(room_id)
#     if not room:
#         print(f"房间 ID {room_id} 不存在'")
#         return
#
#     # 检查房间容量
#     try:
#         members = json.loads(room.members) if isinstance(room.members, str) else room.members
#     except json.JSONDecodeError:
#         members = {}
#         print(f"解析房间 {room_id} 的 members 字段失败: {room.members}")
#     if len(members) >= room.max_players:
#         emit('join_room_result', {'success': False, 'error': '房间已满'})
#         return
#
#     # 检查用户是否已在房间中（字典结构）
#     if str(user_id) in members:
#         emit('join_room_result', {'success': False, 'error': '用户已在房间中'})
#         return
#
#         # 查询用户是否已经关联过这个房间   or  当前是否已经在别的房间中（待补充）
#         # existing_record = RoomPlayer.query.filter_by(user_id=user_id, room_id=room_id).first()
#         # if existing_record is None:
#         #     # 插入 user_room 关联记录
#         #     new_roomuser = RoomPlayer(user_id=user_id, room_id=room_id,nickname=nickname)
#
#     # 开始数据库事务将用户与房间进行绑定
#     try:
#         with db.session.begin_nested():
#             # 创建 RoomPlayer 记录
#             new_room_player = RoomPlayer(
#                 user_id=user_id,
#                 room_id=room_id,
#                 nickname=user.nickname,
#                 avatar=user.avatar,
#                 is_owner=False,
#                 status=1,
#                 join_time=datetime.now()
#             )
#             db.session.add(new_room_player)
#             # 更新 Room.members 字段（字典结构）
#             new_member = {
#                     'user_id': user_id,
#                     'nickname': user.nickname,
#                     'avatar': user.avatar,
#                     'is_owner': False,
#                     'join_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#             }
#             members[str(user_id)] = new_member  # 使用用户 ID 作为键
#             room.members = json.dumps(members)
#             # 更新房间当前人数
#             room.current_players = len(members)
#             db.session.commit()
#             # 加入 Socket.IO 房间
#             flask_socketio.join_room(room_id)
#             # 通知房间内所有用户有新成员加入
#             print("---+++",members)
#             emit('user_joined', new_member, room=room_id)
#     except Exception as e:
#         db.session.rollback()
#         print(f"加入房间失败: {e}")
#     # emit('room_info', {'members': [member]}, room=room_id)
#     # 以下这段是根据中间表，找到所有房间中的人，然后通过循环返回所有人的信息
#     # members = RoomPlayer.query.filter_by(room_id=room_id).all()
#     # members_info = [{'player_id': member.player_id, 'name': member.player.name, 'avatar': member.player.avatar} for member in members]
#     # 更新room表的用户列表


# WebSock监听（ROOM界面）
@socketio.on('connect')
def handle_connect():
    print("hi")
    # 获取当前客户端的Socket ID
    # current_sid = request.sid
    # print(f"sid: {current_sid}已连接")
    # """客户端连接时验证身份"""
    # # 从查询参数获取 Token（前端连接时需携带）
    # token = request.args.get('token')
    # if not token:
    #     return False  # 拒绝连接
    #
    # try:
    #     # 验证并解析 Token
    #     data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
    #     user_id = data.get('user_id')
    #     if not user_id:
    #         return False
    #
    #     # 记录当前 Socket 与用户的映射
    #     user_rooms[request.sid] = {'user_id': user_id}
    #     print(f"用户 {user_id} 已连接，Socket ID: {request.sid}")
    #
    # except jwt.ExpiredSignatureError:
    #     return False  # Token 过期
    # except jwt.InvalidTokenError:
    #     return False  # 无效 Token


# WebSocket: 初始化房间
@socketio.on('init_room')
def handle_init_room(data):
    print("return init_room")
    room_id = data.get('roomId')
    if not room_id:
        return emit('error', {'message': '缺少房间ID'})
    #加入房间？？？？？？？？？？？？
    flask_socketio.join_room(room_id)
    # 查询房间信息JSON 字段
    room = Room.query.get(room_id)
    if not room:
        return emit('error', {'message': '房间不存在'})
    try:
        # 解析members字段,如果是字符串则使用jsonload解析 否则直接加载
        members = json.loads(room.members) if isinstance(room.members, str) else room.members
        if not isinstance(members, dict):  # 确保是字典结构
            members = {}
    except:
        members = {}
    # # 发送房间信息
    res_data={"room_id":room_id,"members":members}
    emit('update_members', res_data,room=room_id)





    # 获取对局记录
    if not room_id:
        return jsonify({'error': '缺少room_id参数'}), 400
    # 查询该房间所有已结束的对局，按时间倒序  ——  没必要  这个字段可以删除了
    rounds = Round.query.filter_by(room_id=room_id,).order_by(Round.end_time.desc()).all()
    history =[{
        'id': r.id,
        'time': r.start_time.strftime("%Y-%m-%d %H:%M:%S") if r.start_time else None,
        # 'end_time': r.end_time.isoformat() if r.end_time else None,
        "scores": r.score_detail,
        # 'winner_id': r.winner_id
    } for r in rounds]
    print(history)
#     history = [
#     # 第一局数据
#     {
#         "time": "14:30:25",  # 时间格式（小时:分钟:秒）
#         "scores": {
#             "1001": 15,   # 用户ID: 分数（示例用户1）
#             "1002": -5,   # 示例用户2（非赢家，分数可能为负）
#             "1003": -5,   # 示例用户3
#             "1004": -5    # 示例用户4
#         }
#     },
#     # 第二局数据
#     {
#         "time": "14:45:10",
#         "scores": {
#             "1001": -8,
#             "1002": 24,   # 本局赢家
#             "1003": -8,
#             "1004": -8
#         }
#     }
# ]

    history_data = {"room_id": room_id, "history": history}
    emit('update_history', history_data, room=room_id)
    # print(history_data)


# # 广播房间信息
# def get_room_members(room_id):
#     members = RoomPlayer.query.filter_by(room_id=room_id).all()
#     return [{'player_id': member.player_id, 'name': member.player.name} for member in members]


# WebSocket: 离开房间
@socketio.on('leave_room')
def handle_leave_room(data):
    print("leave")
    print(data)
    room_id = data.get('room_id')
    user_id = data.get('user_id')
    # 验证参数
    if not room_id or not user_id:
        print("++**********************************", "缺少必要必要参数")
        return emit('error', {'message': '缺少必要必要参数'})

    # 查询房间和用户信息
    room = Room.query.get(room_id)
    user = User.query.get(user_id)

    if not room or not user:
        print("++**********************************", '房间或用户不存在')
        return emit('error', {'message': '房间或用户不存在'})

    # 查询用户在房间中的关联记录
    room_player = RoomPlayer.query.filter_by(
        room_id=room_id,
        user_id=user_id
    ).first()
    if not room_player:
        print("++**********************************", '用户未加入此房间')
        return emit('error', {'message': '用户未加入此房间'})

    try:
        # 1. 解析房间成员信息
        try:
            # 从Room表中获取当前成员列表
            members = json.loads(room.members) if isinstance(room.members, str) else room.members
            if not isinstance(members, dict):
                members = {}
        except:
            members = {}


        # 2. 更新用户状态为"已离开"（保留记录但标记状态）
        room_player.status = 3  # 3: 已离开
        room_player.leave_time = datetime.now()

        # 3. 从members中直接删除该用户
        user_id_str = str(user_id)
        if user_id_str in members:
            # 直接删除成员（不再保留在列表中）
            del members[user_id_str]
            # 同步到数据库
            room.members = json.dumps(members)
            # 更新当前房间人数（剩余在线人数）
            online_count = len(members)  # 此时members中仅存未离开的用户
            room.current_players = online_count
            print(f"用户 {user_id} 已从房间成员列表中删除，当前剩余: {members}")

        # 4. 如果离开的是房主，转移房主权限
        if room_player.is_owner:
            # 查询房间内其他在线玩家
            other_players = RoomPlayer.query.filter(
                RoomPlayer.room_id == room_id,
                RoomPlayer.user_id != user_id,
                RoomPlayer.status == 1  # 1: 在线
            ).all()

            if other_players:
                # 选择第一个在线玩家作为新房主
                new_owner = other_players[0]
                new_owner.is_owner = True
                # 更新members字段中的房主标识
                if str(new_owner.user_id) in members:
                    members[str(new_owner.user_id)]['is_owner'] = True
                    room.members = json.dumps(members)  # 同步到数据库
                # 广播房主变更
                emit('new_owner', {'user_id': new_owner.user_id}, room=room_id)
            else:
                # 没有其他在线玩家，关闭房间
                room.status = 3  # 3: 已结束
                emit('room_closed', {'reason': '所有玩家已离开'}, room=room_id)

        # 5. 检查房间是否为空（无在线玩家）
        active_players = RoomPlayer.query.filter(
            RoomPlayer.room_id == room_id,
            RoomPlayer.status == 1
        ).count()
        if active_players == 0 and room.status == 1:  # 1: 等待中
            room.status = 3  # 3: 已结束
            emit('room_closed', {'reason': '所有玩家已离开'}, room=room_id)

        # 提交数据库更改
        db.session.commit()

        # 6. 广播用户离开的消息（包含最新状态）
        emit('user_left', {'user_id': user_id}, room=room_id)

        # 7. 让用户离开WebSocket房间
        leave_room(room_id)

        # 8. 返回成功响应
        emit('leave_success', {'message': '成功离开房间'})

    except Exception as e:
        db.session.rollback()
        print(e)
        emit('error', {'message': f'服务器内部错误: {str(e)}'})


# WebSocket: 更新分数
@socketio.on('update_score')
def handle_update_score(data):
    room_id = data.get('room_id')
    user_id = data.get('user_id')
    score = data.get('score')
    # if room_id in rooms and user_id in rooms[room_id]['scores']:
    #     rooms[room_id]['scores'][user_id] += score
    #     rooms[room_id]['history'].append({  # 记录对局历史
    #         'user_id': user_id,
    #         'score': score
    #     })
    #     # 广播更新后的房间信息
    #     socketio.emit('room_info', rooms[room_id], room=room_id)

# @socketio.on('disconnect')
# def handle_disconnect():
#     """用户断开连接时清理资源"""
#     current_socket_id = request.sid
#     user_info = user_rooms.pop(current_socket_id, None)
#
#     if user_info and 'room_id' in user_info:
#         room_id = user_info['room_id']
#         user_id = user_info['user_id']
#
#         # 更新用户状态为离线
#         member = RoomPlayer.query.filter_by(
#             room_id=room_id,
#             user_id=user_id,
#             status=1
#         ).first()
#
#         if member:
#             member.status = 2  # 离线
#             db.session.commit()
#
#             # 通知房间内其他用户
#             emit('user_status_change', {
#                 'user_id': user_id,
#                 'status': 'offline'
#             }, room=room_id)
#
#         leave_room(room_id)
#         print(f"用户 {user_id} 离开房间 {room_id}")



# @bp.route('/joinroom', methods=['POST'])
# def joinroom():
#     data = request.json
#     print(data)
#     room_id = data.get('room_id')
#     # joinroom为库封装的方法可以创建一个Websocket房间————这里是指让当前连接的客户端加入指定房间
#     join_room(room_id)
#     user_id = data.get('user_id')
#     user = UserModel.query.get(user_id)
#     member = {"id": user_id, "name": user.username, "avatar": user.user_img}
#     print(member)
#     emit('room_info', member, room=room_id)
#     # try:
#     #     data = request.json
#     #     if not data:
#     #         return jsonify({'success': False, 'message': '请求数据为空'}), 400
#     #
#     #     room_id = data.get('room_id')
#     #     user_id = data.get('user_id')
#     #     if not room_id or not user_id:
#     #         return jsonify({'success': False, 'message': '缺少必要参数'}), 400
#     #
#     #     room = RoomModel.query.get(room_id)
#     #     if not room:
#     #         return jsonify({'success': False, 'message': '房间不存在'}), 404
#     #     player = UserModel.query.get(user_id)
#     #     if not player:
#     #         return jsonify({'success': False, 'message': '玩家不存在'}), 404
#     #
#     #     # 检查玩家是否已经加入房间
#     #     if room_userModel.query.filter_by(room_id=room_id, user_id=user_id).first():
#     #         return jsonify({'success': False, 'message': '玩家已加入房间'}), 400
#     #
#     #     # 否则将玩家加入房间
#     #     room_player = room_userModel(room_id=room_id, user_id=user_id)
#     #     db.session.add(room_player)
#     #     db.session.commit()
#     #
#     #     # 广播给房间内的所有用户
#     #     socketio.emit('player_joined', {'user_id': user_id, 'name': player.username, 'avatar': player.user_img}, room=room_id)
#     #     return jsonify({'success': True, 'message': '加入房间成功'})
#     # except Exception as e:
#     #     print(f"加入房间时发生错误: {e}")
#     #     db.session.rollback()
#     #     return jsonify({'success': False, 'message': '加入房间失败'}), 500

# -------------------------------------------结算本局-------------------------------------
@bp.route('/check_room', methods=['POST'])
def check_room():
    time.sleep(10000)
    data = request.get_json()
    room_id = data.get('room_id')
    if not room_id:
        return jsonify({'exists': False, 'error': '缺少房间ID'}), 400
    room = Room.query.get(room_id)
    return jsonify({'exists': bool(room)})

# 添加获取房间详情的接口
@bp.route('/get_room_info/<room_id>', methods=['GET'])
def get_room_info(room_id):
    room = Room.query.get(room_id)
    if not room:
        return jsonify({'error': '房间不存在'}), 404
    print({
        'id': room.id,
        'current_game': room.current_game+1
    })
    return jsonify({
        'id': room.id,
        'current_game': room.current_game+1,
        # 'rule_config_id': room.rule_config_id,
        # 其他需要返回的字段...
    })
#已废弃
@bp.route('/getroomusers', methods=['GET'])
def get_room_users():

    room_id = request.args.get('roomId')
    round_number = request.args.get('roundNumber')

    # 查询对局基础信息
    round = Round.query.filter_by(
        room_id=room_id,
        round_number=round_number
    ).first()

    # 查询关联玩家分数
    players = RoomPlayer.query.filter_by(room_id=room_id).all()

    return jsonify({
        'players': [{
            'userId': p.user_id,
            'nickname': p.nickname,
            'avatar': p.avatar,
            # 'score': p.score,
            # 'isWinner': False
        } for p in players]
    })

@bp.route('/rounds/settle', methods=['POST'])
def settle_round():

    try:
        # 1. 接收前端传入的数据
        data = request.get_json()
        print("----------------settle------------------", data)
        room_id = data.get('roomId')
        round_number = data.get('roundNumber')
        players = data.get('players', [])  # 玩家列表：[{userId, score, isWinner}, ...]

        # 2. 基础参数校验
        if not all([room_id, round_number, players]):
            return jsonify({'error': '缺少必要参数（房间ID/局数/玩家数据）'}), 400
        # if len(players) != 4:  # 强制4人房（按你的规则）
        #     return jsonify({'message': '必须为4人房（1赢家+3非赢家）'}), 400

        # 3. 提取赢家和非赢家（并校验规则）
        winners = [p for p in players if p.get('isWinner') is True]
        if len(winners) != 1:
            return jsonify({'error': '必须且只能指定1个赢家'}), 400
        winner = winners[0]  # 唯一赢家
        non_winners = [p for p in players if p.get('isWinner') is False]  # 3个非赢家

        # 4. 校验分数合法性（必须为非负整数）
        for p in players:
            if not isinstance(p.get('score'), int) or p['score'] < 0:
                return jsonify({'error': f'玩家{p["userId"]}的分数必须为非负整数'}), 400

        # 5. 计算每个玩家的单局净收益（核心逻辑）
        # 先整理所有玩家的输入分数（用于非赢家的支出计算）
        all_player_scores = {p['userId']: p['score'] for p in players}
        # 计算每个玩家的净收益
        settlement_results = []
        for p in players:
            user_id = p['userId']
            input_score = p['score']  # 前端输入的分数
            is_winner = p['isWinner']

            if is_winner:

                net_gain = input_score * 3
            else:

                other_players = [uid for uid in all_player_scores if uid != user_id]
                total_outcome = sum(all_player_scores[uid] for uid in other_players)  # 总支出
                net_gain = input_score - total_outcome  # 净收益

            settlement_results.append({
                'user_id': user_id,
                'input_score': input_score,
                'net_gain': net_gain,
                'is_winner': is_winner
            })
        # 新增. 直接基于players构建score_detail（以user_id为键）
        score_detail = {}
        for p in players:
            user_id = p['userId']
            input_score = p['score']
            is_winner = p['isWinner']
            if is_winner:
                # 赢家：净收益 = 自身输入分数 × 3
                net_gain = input_score * 3
            else:
                # 非赢家：净收益 = 自身输入分数 - 向其他所有玩家支付的分数总和
                # 其他玩家 = 所有玩家 - 自己
                other_players = [uid for uid in all_player_scores if uid != user_id]
                total_outcome = sum(all_player_scores[uid] for uid in other_players)
                net_gain = input_score - total_outcome
            # 构建score_detail
            score_detail[str(user_id)] = {  # user_id转为字符串作为键
                'input_score': input_score,
                'net_gains': net_gain,
                'isWinner': is_winner
            }
        # 6. 存储到数据库（更新rounds表和room_players表）
        with db.session.begin_nested():
            # 1、检查轮次是否已存在，避免重复创建
            round_record = Round.query.filter_by(room_id=room_id, round_number=round_number).first()
            if not round_record:
                # 创建新轮次记录
                round_record = Round(
                    room_id=room_id,
                    round_number=round_number,
                    dealer_id=players[0]['userId'],
                    status=2  # 默认为已结束
                )
            db.session.add(round_record)
            # 关键操作：将score_detail赋值给数据库字段
            round_record.score_detail = score_detail  # 这一行确保数据落库


            # （2）更新rounds表的分数和赢家（按用户ID顺序对应user1~user4_score）
            sorted_players = sorted(players, key=lambda x: x['userId'])
            for i in range(4):
                if i < len(sorted_players):
                    # 给user1_score~user4_score赋值（对应排序后的玩家）
                    setattr(round_record, f'user{i+1}_score', sorted_players[i]['score'])
                else:
                    setattr(round_record, f'user{i+1}_score', 0)  # 不足4人则补0


            # 设置赢家ID和结束时间
            round_record.winner_id = winner['userId']
            round_record.end_time = datetime.now()
            round_record.status = 2  # 标记为已结束

            # # （3）更新room_players表的累计分数（总分数=历史分数+本局净收益）
            # for res in settlement_results:
            #     room_player = RoomPlayer.query.filter_by(
            #         room_id=room_id,
            #         user_id=res['user_id']
            #     ).first()
            #     if room_player:
            #         # 累计分数 = 现有分数 + 本局净收益
            #         room_player.score += res['net_gain']
            #     else:
            #         # 理论上不会走到这里（玩家必须在房间中才能结算）
            #         return jsonify({'error': f'玩家{res["user_id"]}不在房间中'}), 400

            # （4）更新房间的当前局数（rooms表）
            room = Room.query.get(room_id)
            if room:
                room.current_game = round_number  # 当前局数更新为已结算的局数
                if room.total_games < round_number:
                    room.total_games = round_number  # 更新总局数

        # 提交事务
        db.session.commit()
        # socketio.emit('settlement_completed',  room=room_id)  # 广播给房间内所有连接
        # 7. 返回成功结果
        return jsonify({
            'status': 'success',
            'message': '结算成功',
            'data': {
                'round_number': round_number,
                'settlement': settlement_results,  # 返回单局结算详情
                'score_detail': score_detail
            }
        })

    except Exception as e:

        db.session.rollback()
        print(f'结算失败：{str(e)}')
        return jsonify({'error': f'服务器内部错误：{str(e)}'}), 500

# @socketio.on('roundpay_update')
# def handle_roundpay_update(data):
#     print("roundpay更新数据：",data)
#     room_id = data['room_id']
#     # 广播给房间内其他用户
#     emit('roundpay_update', data, room=room_id, include_self=False)
# ********************************历史记录******************************************
@bp.route('/rounds/history', methods=['GET'])
def get_round_history():
    room_id = request.args.get('room_id')
    if not room_id:
        return jsonify({'error': '缺少room_id参数'}), 400
    # 查询该房间所有已结束的对局，按时间倒序  ——  没必要  这个字段可以删除了
    rounds = Round.query.filter_by(room_id=room_id,).order_by(Round.end_time.desc()).all()
    return jsonify([{
        'id': r.id,
        'start_time': r.start_time.isoformat() if r.start_time else None,
        'end_time': r.end_time.isoformat() if r.end_time else None,
        'user1_score': r.user1_score,
        'user2_score': r.user2_score,
        'user3_score': r.user3_score,
        'user4_score': r.user4_score,
        'winner_id': r.winner_id
    } for r in rounds])



#监听用户提交分数
@socketio.on('user_score_submit')
def user_score_submit(data):
    # 解析前端发送的数据
    room_id = data['room_id']
    round_number = data['roundNumber']
    user_id = data['user_id']
    score = data['score']
    is_winner = data['isWinner']
    submittedUsers = data['submittedUsers']
    print("部分结算", data)
    res_data = {
        'room_id': room_id,  # 必须包含房间ID
        'roundNumber': round_number,  # 必须包含轮次
        'userId': user_id,  # 用户ID
        'score': score,  # 分数（数字类型）
        'isWinner': is_winner,  # 是否为赢家
        'submittedUsers':submittedUsers
    }
    emit('user_score_submitted', res_data, room=room_id)

#监听所有用户提交完成
@socketio.on('settlement_all_complet')  # 前端加入房间后主动触发此事件
def settlement_all_complet(data):
    # {room_id, roundNumber, allData} = data;
    print("settlement_all_complet执行")
    room_id = data['room_id']
    roundNumber = data['roundNumber']
    res_data = {
        'room_id': room_id,
        'roundNumber': roundNumber,
    }
    emit('settlement_all_completed', res_data, room=room_id)  # 广播给房间内所有连接




